package com.kkd.kkdapp.activity;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.Verification;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

/*****
 * 
 * @Date 2016-03-21
 * 
 * @author mty
 * 
 * @Name 重置密码
 * 
 */
public class ResetPswStepActivity extends BaseActivity implements
		OnClickListener {
	private static final int ON_TIMER_STEP = 1;
	private static final int ON_GET_VERIFICATION_SUCCESS = 6;
	private static final int ON_GET_VERIFICATION_FAILURE = 7;
	private static final int ON_GET_YUYINCODE_SUCCESS = 8;
	private static final int ON_GET_YUYINCODE_FAILURE = 9;
	private RelativeLayout back; // 返回键
	private EditText phone_et; // 手机号
	private RelativeLayout get_code; // 获取验证码或重发验证码
	private int count;
	private Timer timer;
	private TimerTask mTimerTask;
	private TextView anew_tv;
	private TextView verification_time1;
	private TextView verification_time2;
	private TextView sendphone_tv;
	private String summary;
	private String sendMessage;
	private Button register_button; // 提交按钮
	private EditText pwd_et; // 第一次输入密码
	private EditText pwd_et_two; // 再次输入密码
	private EditText code_et; // 验证码
	private Dialog loadDialog;
	private String phone; // 注册手机号
	private TextView phone_tv;
	private boolean fixed;
	private int statusCode;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case ON_TIMER_STEP:
				if (count != 0) {
					verification_time1.setText("" + count);
					// if (count < 40) {
					// anew_tv.setVisibility(View.VISIBLE);
					// // verification_time1.setVisibility(View.GONE);
					// // verification_time2.setVisibility(View.GONE);
					// }
					count--;
				} else if (count == 0) {
					verification_time1.setVisibility(View.GONE);
					verification_time2.setVisibility(View.GONE);
					anew_tv.setVisibility(View.VISIBLE);
					if (mTimerTask != null) {
						mTimerTask.cancel();
						mTimerTask = null;
					}
				}
				break;
			case ON_GET_VERIFICATION_SUCCESS:
				showToast(summary);
				if (mYuyinCodeDialog != null) {
					mYuyinCodeDialog.cancel();
					mYuyinCodeDialog = null;
				}
				break;
			case ON_GET_YUYINCODE_SUCCESS:
				showToast(summary);
				if (mYuyinCodeDialog != null) {
					mYuyinCodeDialog.cancel();
					mYuyinCodeDialog = null;
				}
				break;
			case ON_GET_VERIFICATION_FAILURE:
				if (mYuyinCodeDialog != null) {
					mYuyinCodeDialog.cancel();
					mYuyinCodeDialog = null;
				}
				showToast(sendMessage);
				count = 0;
				sendphone_tv.setVisibility(View.GONE);
				verification_time1.setVisibility(View.GONE);
				// verification_time2.setVisibility(View.GONE);
				anew_tv.setVisibility(View.VISIBLE);
				if (statusCode == 231) { // 短信超限
					handler.postDelayed(new Runnable() {

						@Override
						public void run() {
							finish();
						}
					}, 2000);
				}
				break;
			case ON_GET_YUYINCODE_FAILURE:
				if (mYuyinCodeDialog != null) {
					mYuyinCodeDialog.cancel();
					mYuyinCodeDialog = null;
				}
				showToast(sendMessage);
				count = 0;
				sendphone_tv.setVisibility(View.GONE);
				verification_time1.setVisibility(View.GONE);
				// verification_time2.setVisibility(View.GONE);
				anew_tv.setVisibility(View.VISIBLE);

				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reset_psw_step);
		initView();
		setListener();
	}

	@Override
	protected void onDestroy() {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		super.onDestroy();
	}

	/************
	 * 初始化控件
	 ************/
	public void initView() {
		back = (RelativeLayout) this.findViewById(R.id.back);
		phone_et = (EditText) this.findViewById(R.id.phone_et);
		get_code = (RelativeLayout) this.findViewById(R.id.get_code);
		verification_time1 = (TextView) this
				.findViewById(R.id.verification_time1);
		verification_time2 = (TextView) this
				.findViewById(R.id.verification_time2);
		anew_tv = (TextView) this.findViewById(R.id.anew_tv);
		sendphone_tv = (TextView) findViewById(R.id.sendphone_tv);
		code_et = (EditText) this.findViewById(R.id.code_et);
		pwd_et = (EditText) this.findViewById(R.id.pwd_et);
		register_button = (Button) this.findViewById(R.id.register_button);
		pwd_et_two = (EditText) this.findViewById(R.id.pwd_et_two);
		phone_tv = (TextView) this.findViewById(R.id.phone_tv);
		Intent intent = this.getIntent();
		fixed = intent.getBooleanExtra("fixed", false);
		if (fixed) {
			phone_tv.setVisibility(View.VISIBLE);
			phone_et.setVisibility(View.GONE);
			phone_tv.setText(PreferenceUtils.getInstance().getPhone(this));
			sendphone_tv.setTextColor(0xff6c54b6);
		} else {
			phone_tv.setVisibility(View.GONE);
			phone_et.setVisibility(View.VISIBLE);
		}
	}

	/************
	 * 注册监听事件
	 ************/
	public void setListener() {
		back.setOnClickListener(this);
		register_button.setOnClickListener(this);
		anew_tv.setOnClickListener(this);
		sendphone_tv.setOnClickListener(this);
		phone_et.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (TextUtils.isEmpty(phone_et.getText().toString())) {
					sendphone_tv.setTextColor(0xffb5b5b5);
				} else {
					sendphone_tv.setTextColor(0xff6c54b6);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
	}

	@Override
	public void onClick(View v) {

		String phone = "";
		if (fixed) {
			phone = phone_tv.getText().toString();
		} else {
			phone = phone_et.getText().toString();
		}

		switch (v.getId()) {
		case R.id.back: // 返回
			finish();
			break;
		case R.id.sendphone_tv:
			ActionSendVerification(phone);

			break;
		case R.id.register_button:
			submit();
			break;
		case R.id.anew_tv:
			SystemUtils.onEvent("Register_NOPhoneCode", 1);
			if (count == 0) {
				showYuyinCodeDialog(phone);
			} else {
				sendYuyinRequest(phone);
				SystemUtils.onEvent("Register_TelCode", 1);
			}
		}

	}

	protected void ActionSendVerification(String phone) {
		if (TextUtils.isEmpty(phone)) {
			showToast("请输入正确的手机号");
			return;
		} else if (!isMobileNO(phone)) {
			showToast(R.string.phone_on);
			return;
		} else {
			if (count == 0) {
				sendMobileCode(phone);
				count = 60;
				countDown();
			}
		}
	}

	/********
	 * 提交
	 *******/
	public void submit() {
		String phone = "";
		if (fixed) {
			phone = phone_tv.getText().toString();
		} else {
			phone = phone_et.getText().toString();
		}
		String code = code_et.getText().toString();
		String psw = pwd_et.getText().toString();
		String pwd_et_t = pwd_et_two.getText().toString();
		if (TextUtils.isEmpty(phone)) {
			showToast("请输入您的手机号码");
		} else if (!isMobileNO(phone)) {
			showToast(R.string.phone_on);
		} else if (TextUtils.isEmpty(code)) {
			showToast("请输入您的验证码");
		} else if (TextUtils.isEmpty(psw)) {
			showToast("请输入设置密码");
		} else if (psw.length() < 6) {
			showToast("密码长度不能小于6位");
		} else if (TextUtils.isEmpty(pwd_et_t)) {
			showToast("请再次输入密码");
		} else if (pwd_et_t.length() < 6) {
			showToast("密码长度不能小于6位");
		} else if (psw.equals(pwd_et_t)) {
			updateSucceed(phone);
		} else {
			showToast("两次输入密码不一致");
		}
	}

	/************
	 * 倒计时
	 ************/
	public void countDown() {
		sendphone_tv.setVisibility(View.GONE);
		verification_time1.setVisibility(View.VISIBLE);
		verification_time1.setText("" + count);
		verification_time2.setVisibility(View.VISIBLE);
		anew_tv.setVisibility(View.GONE);
		if (timer == null)
			timer = new Timer();
		if (mTimerTask == null)
			mTimerTask = new TimerTask() {

				@Override
				public void run() {
					handler.sendEmptyMessage(ON_TIMER_STEP);
				}
			};
		timer.schedule(mTimerTask, 00, 1000);
	}

	/**
	 * 发送验证码
	 */
	public void sendMobileCode(String mPhone) {
		LogUtil.e("mPhonesend", mPhone);
		KkdHttpMagager.getInstance().getWithdrawSendMobileCodeManager(mPhone,
				String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							phone = data.getString("phone");
							summary = data.getString("summary");
							handler.sendEmptyMessage(ON_GET_VERIFICATION_SUCCESS);
						} catch (JSONException e) {

							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						sendMessage = desc;
						ResetPswStepActivity.this.statusCode = statusCode;
						handler.sendEmptyMessage(ON_GET_VERIFICATION_FAILURE);
						// if (statusCode == 229) { // 手机号未绑定
						// showToast(desc);
						// sendphone_tv.setText(desc);
						// handler.postDelayed(new Runnable() {
						//
						// @Override
						// public void run() {
						// finish();
						// }
						// }, 2000);
						// } else if (statusCode == 231) { // 短信超限
						// LogUtil.e("测试", "5");
						// showToast(desc);
						// sendphone_tv.setText(desc);
						// handler.postDelayed(new Runnable() {
						//
						// @Override
						// public void run() {
						// finish();
						// }
						// }, 2000);
						// } else if (statusCode == 230) { // 验证码未过期
						//
						// showToast(desc);
						// sendphone_tv
						// .setTextColor(ResetPswStep2Activity.this
						// .getResources().getColor(
						// R.color.red));
						// sendphone_tv.setText(desc);
						// } else {
						// showToast(desc);
						// }
						// if (loadDialog != null) {
						// loadDialog.dismiss();
						// }
					}
				});
	}

	/************
	 * 修改登录密码
	 ************/
	public void updateSucceed(String mPhone) {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(this, "努力加载中....");
		LogUtil.e("mPhoneupdate", mPhone);
		KkdHttpMagager.getInstance().getResetPswStep3Manager(mPhone,
				pwd_et.getText().toString(), pwd_et_two.getText().toString(),
				code_et.getText().toString(), String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {

						try {
							showToast(R.string.password_reset);
							handler.postDelayed(new Runnable() {

								@Override
								public void run() {
									finish();
								}
							}, 2000);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if (loadDialog != null) {
							loadDialog.dismiss();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						showToast(desc);
						if (loadDialog != null) {
							loadDialog.dismiss();
						}
					}
				});
	}

	private Dialog mYuyinCodeDialog;

	protected void showYuyinCodeDialog(final String phone) {
		if (mYuyinCodeDialog != null) {
			mYuyinCodeDialog.cancel();
			mYuyinCodeDialog = null;
		}

		mYuyinCodeDialog = DialogUtils.YuyinCodeDialog(this, phone_et.getText()
				.toString(), new OnClickListener() {

			@Override
			public void onClick(View v) {
				sendYuyinRequest(phone);
				SystemUtils.onEvent("Register_TelCode", 1);
			}
		}, new OnClickListener() {

			@Override
			public void onClick(View v) {
				SystemUtils.onEvent("Register_ReMessageCode", 1);
				if (TextUtils.isEmpty(phone)) {
					showToast("请输入正确的手机号");
					return;
				} else if (!isMobileNO(phone)) {
					showToast(R.string.phone_on);
					return;
				} else {
					if (count == 0) {
						sendMobileCode(phone);
						count = 60;
						countDown();
					}
				}

			}
		}, new OnClickListener() {

			@Override
			public void onClick(View v) {
				mYuyinCodeDialog.dismiss();
			}
		});
		mYuyinCodeDialog.show();

	}

	/**
	 * 发送语音验证码
	 */
	public void sendYuyinRequest(String phone) {
		KkdHttpMagager.getInstance().getYuyinRequest2("", phone,
				Verification.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						Verification verification = (Verification) responseBody;
						summary = verification.getSummary();
						handler.sendEmptyMessage(ON_GET_YUYINCODE_SUCCESS);

					}

					@Override
					public void onFailure(int statusCode, String desc) {
						sendMessage = desc;
						handler.sendEmptyMessage(ON_GET_YUYINCODE_FAILURE);
					}
				});
	}
}
